package com.aoxin.controller.pay.alipayNotify;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
//import com.alipay.api.AlipayApiException;
//import com.alipay.api.internal.util.AlipaySignature;

@Controller
@RequestMapping("/web/aliPayNotify")
public class MobileNotifyController {
/*	@Autowired
	to do(your service)
	;*/

	@RequestMapping("/mobileNotify")
	@ResponseBody
	public String mobileNotify(HttpServletRequest request, HttpServletResponse response) {
		System.out.println("支付宝异步通知地址");
		Map<String, String> getMap = new HashMap<String, String>();
		Map<String, String[]> maps = request.getParameterMap();
		for (Iterator<String> iter = maps.keySet().iterator(); iter.hasNext();) {
			String name = iter.next();
			String[] values = maps.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
			}
			// 乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
			try {
				valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			getMap.put(name, valueStr);
		}
		boolean signVerified = false;

		System.out.println("map:" + getMap);
//		System.out.println("maps:" + maps.toString());
//		try {
//			signVerified = AlipaySignature.rsaCheckV1(getMap, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.CHARSET,
//					AlipayConfig.SIGNTYPE);
//		} catch (AlipayApiException e) {
//			e.printStackTrace();
//		} // 调用SDK验证签名
		System.out.println("验签是否成功：" + signVerified);
		// 支付宝订单
		String trade_no = getMap.get("trade_no");
		// 商品订单
		String out_trade_no = getMap.get("out_trade_no");
		// 交易状态
		String trade_status = getMap.get("trade_status");
		String notify_id = getMap.get("notify_id");
		System.out.println("====================================================");
		System.out.println("trade_no:" + trade_no + "out_trade_no:" + out_trade_no + "trade_status:" + trade_status
				+ "notify_id:" + notify_id);
		if (trade_status.equals("TRADE_SUCCESS")) {
			System.out.println("交易成功");
			// 修改订单信息
		/*	Integer updateOrder = webService.updateOrder("","","1", trade_no, out_trade_no);
			if (updateOrder > 0) {
				LogUtils.writeLog("交易成功");
			} else {
				LogUtils.writeLog("交易失败");
			}*/
		} else {
			System.out.println("交易状态错误");
		}
		return "true";
	}
}
